<template>
  <div class="container">
    <el-dialog :title="formData.id ? '编辑房产' : '添加房产'" :visible="dialogVisible" width="71%" @close="closeFn">
      <el-form ref="form" :model="formData" :rules="rules" label-width="80px">
        <!-- 经纪 下拉框 -->
        <el-form-item prop="agent" label="经纪">
          <el-select v-model="formData.agent" placeholder="请选择经纪">
            <el-option v-for="item in agentsList" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <!-- 分类 下拉框 -->
        <el-form-item prop="category" label="分类">
          <el-select v-model="formData.category" placeholder="请选择分类">
            <el-option v-for="item in categoriesList" :key="item.id" :label="item.title" :value="item.id" />
          </el-select>
        </el-form-item>
        <!-- 标题 输入框 -->
        <el-form-item prop="title" label="标题">
          <el-input v-model="formData.title" />
        </el-form-item>
        <!-- 标签 -->
        <el-form-item label="标签">
          <el-tag
            v-for="tag in formData.tags"
            :key="tag"
            closable
            :disable-transitions="false"
            @close="handleClose(tag)"
          >
            {{ tag }}
          </el-tag>
          <el-input
            v-if="inputVisible"
            ref="saveTagInput"
            v-model="inputValue"
            class="input-new-tag"
            size="small"
            @keyup.enter.native="handleInputConfirm"
            @blur="handleInputConfirm"
          />

          <el-button v-else class="button-new-tag" size="small" @click="showInput">+ 新标签</el-button>
        </el-form-item>
        <!-- 地址 级联+输入框 -->
        <el-form-item prop="address" label="地址">
          <el-row type="flex" justify="space-between">
            <el-cascader
              v-model="address"
              :options="options"
              placeholder="请选择地址"
              @change="handleChange"
              @focus="getAddress"
            />
            <el-input v-model="formData.address" style="width: 78%" />
          </el-row>
        </el-form-item>
        <!-- 价格 输入框 -->
        <el-form-item prop="price" label="价格">
          <el-input v-model="formData.price" />
        </el-form-item>
        <!-- 描述介绍 文本域 -->
        <el-form-item prop="desc" label="描述">
          <el-input v-model="formData.desc" type="textarea" />
        </el-form-item>
        <!-- 图片 photos 上传图片 多张 -->
        <el-form-item label="图片">
          <el-upload
            action="#"
            list-type="picture-card"
            :file-list="photosList"
            :http-request="photosSuccess"
            :on-remove="removePhotos"
            :limit="4"
          >
            <i class="el-icon-plus" />
          </el-upload>
        </el-form-item>
        <!-- 封面 image 上传图片 一张 -->
        <el-form-item label="封面">
          <el-upload
            action="#"
            list-type="picture-card"
            :file-list="imageList"
            :http-request="imagesSuccess"
            :on-remove="removeImage"
            :limit="1"
          >
            <i class="el-icon-plus" />
          </el-upload>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="closeFn">取 消</el-button>
        <el-button type="primary" @click="confrimFn">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import { addProperty, getProperty, editProperty } from '@/api/property'
import { getAddress } from '@/api/address'
import COS from 'cos-js-sdk-v5'
var cos = new COS({
  SecretId: 'AKIDuhGagYBajdKn49zaw41jCPO7bqqa5LNA',
  SecretKey: 'cy5xb0A7qRoxsYzDCvPdcNtELDqDLEsG'
})
export default {
  props: {
    dialogVisible: {
      type: Boolean,
      required: true
    },
    // 分类列表
    categoriesList: {
      type: Array,
      required: true
    },
    // 经纪列表
    agentsList: {
      type: Array,
      required: true
    },
    propertyId: {
      type: String,
      required: true
    }
  },

  data() {
    // 自定义价格校验
    const checkPrice = (rule, value, callback) => {
      if (value < 0) {
        return callback(new Error('请输入合理的价格'))
      }
      if (value === '0') {
        return callback(new Error('价格不能为0'))
      }
      // 必传callback
      callback()
    }
    return {
      rules: {
        // 经纪
        agent: [{ required: true, message: '经纪不能为空', trigger: 'blur' }],
        // 分类
        category: [{ required: true, message: '分类不能为空', trigger: 'blur' }],
        // 标题
        title: [{ required: true, message: '标题不能为空', trigger: 'blur' }],
        // 地址
        address: [{ required: true, message: '地址不能为空', trigger: 'blur' }],
        // 价格
        price: [
          { required: true, message: '价格不能为空', trigger: 'blur' },
          { validator: checkPrice, trigger: 'blur' }
        ],
        // 描述
        desc: [{ required: true, message: '描述不能为空', trigger: 'blur' }]
      },
      // 控制标签显示
      inputVisible: false,
      // 标签值
      inputValue: '',
      // 上传的封面的图片数组
      imageList: [],
      // 上传的图片的数组
      photosList: [],
      // 表单数据
      formData: {
        title: '',
        desc: '',
        // 封面 一张
        image: '',
        agent: '',
        // 内容为空
        content: '',
        address: '',
        price: '',
        // 图片 多张
        photos: [],
        tags: [],
        category: ''
      },
      // 地址-级联选择器的值
      address: '',
      // 地址配置
      options: []
    }
  },

  methods: {
    // 编辑房产-表单回显
    async getProperty() {
      const res = await getProperty(this.propertyId)
      this.formData = res.data
      // 有图片才回显
      if (this.formData.image) {
        this.imageList.push({ url: this.formData.image })
      }
      if (this.formData.photos) {
        this.formData.photos.forEach((item) => {
          this.photosList.push({ url: item })
        })
      }
    },
    // 表单确认
    async confrimFn() {
      this.formData.photos = []
      console.log(this.formData)
      this.formData.image = this.imageList.length > 0 ? this.imageList[0].url : ''
      this.photosList.forEach((item) => {
        console.log(211, item.url)
        this.formData.photos.push(item.url)
        console.log(213, this.formData.photos)
      })
      // this.formData.photos
      // console.log(211, this.photosList[0].url)

      // 确认前再次校验
      await this.$refs.form.validate()
      // 判断id 有是编辑 没有是新增
      if (this.formData.id) {
        // 编辑
        await editProperty(this.formData)
      } else {
        // 新增
        await addProperty(this.formData)
      }
      // 关闭弹窗 请求父组件更新数据
      this.closeFn()
      this.$emit('getProperty')
    },
    // 图片上传
    photosSuccess(res) {
      // console.log(380, res)
      this.photosList.push({ url: '' })
      cos.putObject(
        {
          Bucket: 'hr-project-1312874530' /* 必须 */,
          Region: 'ap-nanjing' /* 存储桶所在地域，必须字段 */,
          Key: Date.now().toString() /* 必须 */,
          StorageClass: 'STANDARD',
          Body: res.file, // 上传文件对象
          onProgress: ''
        },
        (err, data) => {
          if (!err) {
            console.log(38, data)
            this.photosList[this.photosList.length - 1].url = 'http://' + data.Location
            console.log(241, this.photosList)
            this.formData.photos.push(this.photosList[this.photosList.length - 1].url)
            console.log(243, this.formData.photos)
          }
          // this.$emit('uploadAvatar', this.filelist[0].url)
        }
      )
    },

    // 封面上传
    imagesSuccess(res) {
      this.imageList.push({ url: '' })
      cos.putObject(
        {
          Bucket: 'hr-project-1312874530' /* 必须 */,
          Region: 'ap-nanjing' /* 存储桶所在地域，必须字段 */,
          Key: Date.now().toString() /* 必须 */,
          StorageClass: 'STANDARD',
          Body: res.file, // 上传文件对象
          onProgress: ''
        },
        (err, data) => {
          // 上传成功
          if (!err) {
            this.imageList[0].url = 'http://' + data.Location
            this.formData.image = this.imageList[0].url
          }
        }
      )
    },

    // 移除封面的钩子
    removeImage() {
      this.imageList = []
    },
    // 移除图片的钩子
    removePhotos(file, fileList) {
      this.photosList = fileList
      console.log(279, file, fileList)
    },

    handleClose(tag) {
      this.formData.tags.splice(this.formData.tags.indexOf(tag), 1)
    },

    showInput() {
      this.inputVisible = true
      this.$nextTick((_) => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },

    handleInputConfirm() {
      const inputValue = this.inputValue
      if (inputValue) {
        this.formData.tags.push(inputValue)
      }
      this.inputVisible = false
      this.inputValue = ''
    },
    // 关闭弹窗 清除数据 清空校验
    closeFn() {
      this.formData = {
        title: '',
        desc: '',
        image: '',
        agent: '',
        content: '',
        address: '',
        price: '',
        photos: [],
        tags: [],
        category: ''
      }
      this.$refs.form.resetFields()
      this.address = ''
      this.imageList = []
      this.photosList = []
      this.$emit('closeFn')
    },
    // 地址输入框
    handleChange(value) {
      // 级联选择器得到的值是一个数组 转换为后端需要的字符串
      this.formData.address = value.join(',')
    },

    // 获取省市县
    async getAddress() {
      const res = await getAddress()
      const arr = res.data.districts[0].districts
      arr.forEach((item) => {
        this.options.push({
          // 省
          value: item.name,
          label: item.name,
          children: item.districts.map((item) => {
            return {
              // 市
              value: item.name,
              label: item.name,
              children: item.districts.map((item) => {
                // 县
                return { value: item.name, label: item.name }
              })
            }
          })
        })
      })
    }
  }
}
</script>
<style lang="scss">
// 上传图片组件样式
.avatar-uploader .el-upload {
  border: 1px dashed #a71b1b;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}

// 表单增加标签样式
.el-tag + .el-tag {
  margin-left: 10px;
}
.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
</style>
